package com.swordget.service.impl;

import com.swordget.entity.ColumnDesign;
import com.swordget.entity.TableDesign;
import com.swordget.exception.VerifyFailException;
import com.swordget.service.TableManagerService;
import com.swordget.service.VerifyColumnService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.regex.Pattern;

/**
 * @Author: David
 * @Date: Created in 15:01 2020/3/27
 * @Description: 创建表模板类，如果有不同的需求只需要实现该模板
 * @Modified By:
 * @Version:
 */
public abstract class TableManagerTemplate implements TableManagerService {

    /**
     * 表名正则，用于校验表名
     */
    private final static Pattern tableCheck = Pattern.compile("^\\w{4,30}$");

    /**
     * 字段名正则，用于校验字段名
     */
   // private final static Pattern columnCheck = Pattern.compile("^\\w{1,30}$");

    /**
     * 用于注释校验
     * ^\w{1,20}$|^[\u4e00-\u9fa5,\w]{1,20}$
     */
    private final static Pattern commentCheck = Pattern.compile("^[a-zA-Z0-9\\u4E00-\\u9FA5\\uf900-\\ufa2d_]{1,20}$");

/*    *//**
     * 支持的字段类型
     *//*
    private Set columnTypeSet = new HashSet(Arrays.asList(new String[]{"VARCHAR", "NUMBER"}));

    *//**
     * 支持的日期类型
     *//*
    private Set dateFormatSet = new HashSet(Arrays.asList(new String[]{"yyyy-MM-dd", "yyyy/MM/dd", "yyyy年MM月dd日",
    "yy-MM-dd", "yy/MM/dd", "yy年MM月dd日"}));*/

    @Autowired
    private VerifyColumnService verifyColumnService;

    /**
     * 创建表业务层实现
     * @param tableDesign 表结构
     * @param columns 字段结构
     * @param loginId 操作用户
     * @return
     */
    @Override
    public boolean makeTable(TableDesign tableDesign, List<ColumnDesign> columns, String loginId) {
        //解析表名
        String tableName = tableDesign.getTableEN();
        String tableCom = tableDesign.getTableCN();
        String tableNameUp = tableName.toUpperCase();
        tableDesign.setTableEN(tableNameUp);
        String tableSpace = null;

        //校验用户输入的表名是否合法
        verifyTable(tableName, tableCom);

        //判断数据库是否已经存在表结构
        dataTableExists(tableNameUp);

        //获取用户表空间
        tableSpace = getTableSpace();

        //校验字段结构是否符合要求
        verifyColumnService.verifyColumn(columns);

        //调用数据库服务，生成建表语句执行建表
        return executeMake(tableDesign, columns, tableSpace, loginId);
    }

   // @Override
/*    public boolean modifyTable(TableDesign tableDesign, List<ColumnDesign> columns, String loginId) {
        //解析表名
        String tableName = tableDesign.getTableEN();
        String tableCom = tableDesign.getTableCN();
        String tableNameUp = tableName.toUpperCase();
        tableDesign.setTableEN(tableNameUp);
        String tableSpace = null;

        //校验用户输入的表名是否合法
        verifyTable(tableName, tableCom);

        //判断数据库是否已经存在表结构
        //dataTableExists(tableNameUp);

        //获取用户表空间
        tableSpace = getTableSpace();

        //校验字段结构是否符合要求
        verifyColumn(columns);
        boolean isMake = false;
        if (dropTable(tableDesign)) {
            //调用数据库服务，生成建表语句执行建表
            isMake = executeMake(tableDesign, columns, tableSpace, loginId);
        }
        return isMake;
    }*/


    /**
     * 校验表名是否符合规则
     * @param tableName 表英文名
     * @param tableCom 表中文名
     */
    protected void verifyTable(String tableName, String tableCom) {
        if (StringUtils.isBlank(tableName) || !tableCheck.matcher(tableName).find() ||
                StringUtils.isBlank(tableCom) || !commentCheck.matcher(tableCom).find()) {
            throw new VerifyFailException("校验失败-表名不能为空或格式不正确！");
        }
    }

    /**
     * 对字段格式进行校验
     * @param columns
     * @throws VerifyFailException 校验失败异常
     */
   /* protected void verifyColumn(List<ColumnDesign> columns) {
        for (ColumnDesign column : columns) {
            String name = column.getName().toUpperCase();
            column.setName(name);
            String type = column.getType();
            int width = column.getWidth();
            int point = column.getPoint();
            String notNull = column.getNotNull();
            String comment = column.getComment();
            //是否是搜索条件 N 不是 Y 是
            String search = column.getSearch();
            String contentType = column.getContextType();
            String dateFormat = column.getDateFormat();
            //下拉框url
            String comboUrl = column.getComboUrl();
            //必填项判断
            if (StringUtils.isAnyBlank(name, type, notNull, comment, search, contentType)) {
                throw new VerifyFailException("字段-" + comment + "请输入必填项!");
            }
            //对字段名和字段注释做正则校验
            if (!columnCheck.matcher(name).find() || !commentCheck.matcher(comment).find()) {
                throw new VerifyFailException("字段-" + comment + "名称、注释格式不正确!");
            }
            //下拉框必须填写下拉框地址
            if ("3".equals(contentType) && StringUtils.isBlank(comboUrl)) {
                throw new VerifyFailException("字段-" + comment + "必须填写下拉框值且需用-分割!");
            }
            if ("3".equals(contentType) && !comboUrl.contains("-")) {
                throw new VerifyFailException("字段-" + comment + "下拉框值必须用'-'分割!");
            }
            *//*if ("3".equals(contentType) && StringUtils.isBlank(comboUrl)) {
                throw new VerifyFailException("字段-" + comment + "必须填写下拉框地址api!");
            }*//*
            //日期框格式校验
            if ("2".equals(contentType)) {
                if (StringUtils.isBlank(dateFormat)) {
                    throw new VerifyFailException("字段-" + comment + "必须选择日期格式!");
                }
                if (!dateFormatSet.contains(dateFormat)) {
                    throw new VerifyFailException("字段-" + comment + "应用程式不支持此种日期格式!");
                }
                try {
                    new SimpleDateFormat(dateFormat).format(new Date());
                } catch (IllegalArgumentException e) {
                    throw new VerifyFailException("字段-" + comment + "无法解析这种日期格式!");
                }
            }
            //对字段类型做校验
            if (!columnTypeSet.contains(type)) {
                throw new VerifyFailException("字段-" + comment + "类型不正确!");
            }
            //对字段长度做校验，对于varchar2最大长度4000,对于number最大长度小数位和整数位共不超过38位，小数最大7位
            Integer columnWidth = width;
            Integer columnPoint = point;
            if (VARCHAR2.equals(type)) {
                if (columnWidth <= 0 || columnWidth > 4000) {
                    throw new VerifyFailException("字段-" + comment + "长度不正确!");
                }
            }
            if (NUMBER.equals(type)) {
                if (columnWidth <= 0 || (columnWidth + columnPoint) > 38 || columnPoint > 7 || columnPoint >= columnWidth) {
                    throw new VerifyFailException("字段-" + comment + "比例不正确!");
                }
            }
        }
    }*/

    /**
     * 判断数据表是否在数据库中存在
     * @param tableNameUp
     */
    abstract void dataTableExists(String tableNameUp);

    /**
     * 真正执行创建操作方法,强制用户实现
     * @param tableDesign 表结构
     * @param columnDesigns 字段结构
     * @param tableSpace 表空间
     * @param loginId 操作用户
     * @return
     */
    abstract boolean executeMake(TableDesign tableDesign, List<ColumnDesign> columnDesigns,
                                 String tableSpace, String loginId);

    /**
     * 获取表空间，默认空实现
     * @return
     */
    protected String getTableSpace() {
        return null;
    }

}
